/**
 * @description: toast.
 * @author: pkeros.
 * @date: 30/09/2017.
 * @mail: pkeros@vip.qq.com
 */

import Vue from 'vue'
import ToastComponet from './src/toast.vue'

const pueMapper = ['success', 'info', 'warn', 'danger'];
let defaults = {
  showCancelBtn: false,
  cancelBtnText: '取消',
  confirmBtnText: '确定',
  container: 'body',
  mask: true,
  title: 'Title',
  text: 'Content...',
  type: 'success'
};

let KsToastConstructor = Vue.extend(ToastComponet);

let currentMsg, instance, Toast, id = 0;
let ToastQueue = [];

/**
 * @description 合并选项
 * @param target 需要合并的目标
 * @return {*} 目标
 */
let merge = function(target) {
  for (let i = 1, j = arguments.length; i < j; i++) {
    let source = arguments[i];
    for (let prop in source) {
      if (source.hasOwnProperty(prop)) {
        let value = source[prop];
        if (value !== undefined) {
          target[prop] = value
        }
      }
    }
  }

  return target;
};

/**
 * @description 初始化 Dialog 实例
 */
let initInstance = function () {
  // 实例化 Dialog
  instance = new KsToastConstructor({
    el: document.createElement('div')
  });
  instance.show = false;
};

/**
 * @description 显示队列中的下一个信息
 */
let showNextDialog = function () {
  if (!instance) {
    initInstance()
  }

  // 检测是否阻塞
  if (instance.show ) {
    return
  }

  // 获取当前信息
  currentMsg = ToastQueue.shift()

  // 合并配置项
  let options = currentMsg.options
  for (let prop in options) {
    if (instance.hasOwnProperty(prop)) {
      instance[prop] = options[prop]
    }
  }

  let container = document.querySelector(defaults.container)
  if (container) {
    container.appendChild(instance.$el)
  } else {
    document.body.appendChild(instance.$el)
  }

  Vue.nextTick(() => instance.show = true)
};

/**
 * @description 构造函数
 * @param options {Object} 配置项
 * @constructor
 */
Toast = function (options) {
  // console.log(options)
  // 配置 Dialog 并加入显示队列
  return function (confirmCb, cancelCb) {
    // 参数正确性校验
    if ((typeof confirmCb !== 'undefined' && typeof confirmCb !== 'function')
      || (typeof cancelCb !== 'undefined' && typeof cancelCb !== 'function')) {
      throw new TypeError('KsDialog: Parameter is not correct, member not a function!')
    }

    let config = {
      id: id++,
      options: merge({}, defaults, Toast.defaults || {}, options),
      confirmCb: confirmCb,
      cancelCb: cancelCb,
    };

    ToastQueue.push(config);
    showNextDialog();
    return config
  }
};

/**
 * @description 关闭 Dialog
 */
Toast.close = function () {
  instance.show = false;
  currentMsg = null;
};

/**
 * @description show
 * @param text {String} 显示的内容
 * @param title {String} 标题
 * @param hue {String} 色调
 * @param options {Object} 附加配置项
 */
Toast.show = function (text, position, title, hue, options) {
  if (currentMsg)
    Toast.close();

  return Toast(merge({
    text: text,
    desc:text,
    position:position,
    title: title,
    mask: true,
    type: hue
  }, options))();
};

export default Toast
export { Toast }
